<template>
	<view>
		<view class="cu-bar bg-white">
			<view class="action">{{ title }}</view>
			<view class="action">{{ imgList.length }}/{{ max }}</view>
		</view>
		<view class="cu-form-group">
			<view class="grid col-4 grid-square flex-sub">
				<view class="bg-img" v-for="(item, index) in imgList" :key="index" @tap="ViewImage" :data-url="imgList[index]">
					<image :src="imgList[index]" mode="aspectFill" @error="$_imageError(index)"></image>
					<view class="cu-tag bg-red" @tap.stop="DelImg" :data-index="index" :disabled="disabled"><text class="cuIcon-close"></text></view>
				</view>
				<view class="solids" @tap="ChooseImage" v-if="imgList.length < max" :disabled="disabled"><text class="cuIcon-cameraadd"></text></view>
			</view>
		</view>
	</view>
</template>

<script>
export default {
	props: {
		/**
		 * 标题
		 */
		title: {
			type: String,
			default: ''
		},
		/**
		 * 是否禁用项
		 */
		disabled: {
			type: Boolean,
			default: false
		},
		/**
		 * 最大上传
		 */
		max: {
			type: Number,
			default: 1
		},
		/**
		 * 业务类型
		 */
		type: {
			type: String,
			required: true
		},
		/**
		 * 业务id
		 */
		businessId: {
			type: String,
			required: true
		}
	},
	data() {
		return {
			imgList: []
		};
	},
	methods: {
		ChooseImage() {
			let that = this;
			uni.chooseImage({
				count: 1, //默认9
				sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
				success: res => {
					if (this.imgList.length != 0) {
						this.imgList = this.imgList.concat(res.tempFilePaths);
					} else {
						this.imgList = res.tempFilePaths;
					}
					let formData = { id: this.businessId, type: this.type };
					uni.uploadFile({
						url: this.$store.state.baseUrl + '/user-admin/file/upload',
						filePath: res.tempFilePaths[0],
						name: 'file',
						fileType: 'image',
						formData: formData,
						header: {
							token: uni.getStorageSync(this.GLOBAL.CacheKeys.token)
						},
						success: uploadFileRes => {
							console.log(uploadFileRes.data);
							let res=JSON.parse(uploadFileRes.data);
							if(res.code!="200"){
								uni.showModal({
									content: "上传失败",
									showCancel: false
								});
							}
						},
						fail: err => {
							console.log('uploadImage fail', err);
							uni.showModal({
								content: err.errMsg,
								showCancel: false
							});
						}
					});
				}
			});
		},
		ViewImage(e) {
			uni.previewImage({
				urls: this.imgList,
				current: e.currentTarget.dataset.url
			});
		},
		DelImg(e) {
			uni.showModal({
				title: '召唤师',
				content: '确定要删除这段回忆吗？',
				cancelText: '再看看',
				confirmText: '再见',
				success: res => {
					if (res.confirm) {
						this.imgList.splice(e.currentTarget.dataset.index, 1);
					}
				}
			});
		},
		// 当错误发生时
		$_imageError(index) {
			this.imgList.splice(index,1);
			this.$forceUpdate();
		}
	}
};
</script>

<style></style>
